package yl.hs.bmipfull.security;

import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import yl.hs.bmipfull.utils.ResultCode;
import yl.hs.bmipfull.utils.Tl;
import yl.hs.bmipfull.viewmodels.WebResult;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/*
 * SecurityAuthenticationFailureHandler
 * @category
 * @author 谢景广
 * @date 2021-06-05
 */
public class SecurityAuthenticationFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        WebResult webResult = null;
        if (e instanceof LockedException) {
            webResult = new WebResult(ResultCode.FAIL, "用户账户已锁定，请联系管理员", request.getRequestURL().toString());
        }
        if (e instanceof DisabledException) {
            webResult = new WebResult(ResultCode.FAIL, "用户账户已禁用，请联系管理员", request.getRequestURL().toString());
        }

        if (e instanceof AccountExpiredException) {
            webResult = new WebResult(ResultCode.FAIL, "用户账户已过期，请联系管理员", request.getRequestURL().toString());
        }
        if (webResult != null) {
            Tl.writeObjectToResponse(response, webResult);
        }
    }
}
